import { stationAreaControllerImplAddStationArea as addArea } from '@/services/ess/stationArea';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useIntl } from '@umijs/max';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';

interface AddProps {
  handleAddSubmit: (data: any) => void;
  isArea?: boolean;
  hasArea?: boolean;
  hasDevice?: boolean;
  treeSubDevices?: [];
  queryTreeList: () => void;
}

interface VoltLevelOption {
  label: string;
  value: string | number;
}

const AddAreaModal: React.FC<AddProps> = ({
  handleAddSubmit,
  hasArea,
  hasDevice,
  queryTreeList,
}) => {
  const intl = useIntl();
  const [visible, setVisible] = useState(false);
  const [voltLevels, setVoltLevels] = useState<VoltLevelOption[]>([]);
  const [form] = Form.useForm();
  useEffect(() => {
    fetchDictInfo(DATABASE_TYPE_ENUM.VOLT_LEVEL).then((res) => {
      if (res) {
        res.sort((a, b) => {
          // @ts-ignore
          return parseInt(a.value) - parseInt(b.value); // 将字符串转换为整数进行比较
        });
        setVoltLevels(res || []);
      }
    });
  }, []);

  const showModal = () => {
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const result = await addArea({ ...values });
      if (result.success) {
        message.success(intl.formatMessage({ id: 'siteManage.addAreaSuccess' }));
        handleAddSubmit(result);
        queryTreeList();
        setVisible(false);
        form.resetFields();
      }
    } catch (error) {
      console.error('Failed to add area:', error);
    }
  };

  return (
    <>
      <Button
        type="primary"
        size="middle"
        // disabled={!(isArea || (Array.isArray(treeSubDevices) && treeSubDevices.length === 0))}
        disabled={hasDevice && !hasArea}
        style={{ paddingInline: 15 }}
        onClick={showModal}
      >
        {intl.formatMessage({ id: 'siteManage.addArea' })}
      </Button>
      <Modal
        title={intl.formatMessage({ id: 'siteManage.addArea' })}
        visible={visible}
        onCancel={handleCancel}
        footer={
          <div style={{ textAlign: 'center' }}>
            <Button onClick={handleCancel} style={{ marginRight: 8 }}>
              {intl.formatMessage({ id: 'siteManage.cancel' })}
            </Button>
            <Button type="primary" onClick={handleOk}>
              {intl.formatMessage({ id: 'siteManage.confirm' })}
            </Button>
          </div>
        }
        destroyOnClose
      >
        <Form form={form} layout="vertical" initialValues={{ areaName: '', voltLevel: undefined }}>
          <Form.Item
            label={intl.formatMessage({ id: 'siteManage.areaName' })}
            name="areaName"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.enterAreaName' }),
              },
              {
                max: 32,
                message: intl.formatMessage({ id: 'siteManage.areaN' }),
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={intl.formatMessage({ id: 'siteManage.accessVoltageLevel' })}
            name="voltLevel"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'siteManage.selectVoltage' }),
              },
            ]}
          >
            <Select>
              {voltLevels.map((level) => (
                <Select.Option key={level.value} value={level.value}>
                  {level.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddAreaModal;
